package com.gzcsqic.excelapp.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class FileUtil {

    public static File readFile(String path, String type) throws IOException {
        ClassPathResource classPathResource = new ClassPathResource(path);
        InputStream inputStream = classPathResource.getInputStream();
        File target = File.createTempFile("tempFile", type);
        FileUtils.copyInputStreamToFile(inputStream, target);
        return target;
    }

    public static void copytReeourcesFileToTemp(String fileRoot, String regExpStr, String tempParent) throws Exception {
        try {
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = (Resource[]) resolver.getResources(fileRoot + regExpStr);
            for (Resource resource : resources) {
                File newFile = new File(tempParent, resource.getFilename());
                if (newFile.exists()) {
                    newFile.delete();
                }
                InputStream stream = null;
                try {
                    stream = resource.getInputStream();
                } catch (Exception e1) {

                }
                if (stream == null) {
                    System.out.println("创建文件夹" + resource.getFilename());
                    newFile.mkdirs();
                    Resource[] children = (Resource[]) resolver.getResources(fileRoot + resource.getFilename() + "/" + regExpStr);
                    for (Resource child : children) {
                        copytReeourcesFileToTemp(fileRoot + resource.getFilename() + "/", regExpStr, tempParent + "\\" + resource.getFilename());
                    }
                } else {

                    if (!newFile.getParentFile().exists()) {
                        newFile.getParentFile().mkdir();
                    }
                    FileUtils.copyInputStreamToFile(stream, newFile);
                }
            }
        } catch (Exception e) {
            System.out.println("复制文件出现错误" + e.getMessage());
            throw e;
        }

    }


    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
        String percentEncodedFileName = percentEncode(realFileName);

        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=")
                .append(percentEncodedFileName)
                .append(";")
                .append("filename*=")
                .append("utf-8''")
                .append(percentEncodedFileName);

        response.setHeader("Content-disposition", contentDispositionValue.toString());
    }

    public static String percentEncode(String s) throws UnsupportedEncodingException {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
        return encode.replaceAll("\\+", "%20");
    }


    public static void writeBytes(String filePath, OutputStream os) throws IOException {
        FileInputStream fis = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            IOUtils.close(os);
            IOUtils.close(fis);
        }
    }

    public static String getFileSuffix(String fileName) {
        if (StringUtils.isEmpty(fileName) || fileName.lastIndexOf(".") < 0) {
            return "error";
        }
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

}
